<?php

namespace App\Ant\Jobs;

use App\Models\Company\Archive;
use App\Models\Company\Task;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class FurnitureTaskJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 600;

    protected $task;

    /**
     * 创建一个新的任务实例。
     *
     * @return void
     */
    public function __construct(Task\Furniture $task)
    {
        $this->task = $task;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        if ($this->task->released < $this->task->count) {
            $furnitures = $this->task->furniture()->where('is_state', false)->take($this->task->limit_sum)->get();
            $count = $furnitures->count();
            $this->task->increment('released', $count);
            $furniture_ids = $furnitures->pluck('id')->toArray();
            FurnitureReleaseJob::dispatch($furniture_ids)
                ->onConnection('redis')
                ->onQueue('release')
                ->delay(now()->addSecond(10));
        }
    }
}